package vn.gq.tym.utils;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import android.content.Context;

public class SecurityHelper {
	private Context context;
	private volatile static SecurityHelper instance;
	
	public SecurityHelper(Context ctx) {
		context = ctx;
	}
	
	public static SecurityHelper getInstance(Context ctx) {
		if (instance == null) {
			synchronized (SecurityHelper.class) {
				if (instance == null) {
					instance = new SecurityHelper(ctx);
				}
			}
		}
		return instance;
	}
	
	public String encrypt(String data) throws Exception {
		return new String(Base64.encode(encryptToByte(data), Base64.URL_SAFE));
	}
	
	public byte[] encryptToByte(String data) throws Exception {
		if (data == null || data.equals("")) return "".getBytes();
		InputStream is = context.getAssets().open("public.key");
		if (is == null) throw new FileNotFoundException("public.key");
		byte[] encodeKey = new byte[is.available()];
		is.read(encodeKey);
		X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodeKey);
		KeyFactory kf = KeyFactory.getInstance("RSA");
		PublicKey publicKey = kf.generatePublic(publicKeySpec);
		Cipher pkCipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
		pkCipher.init(Cipher.ENCRYPT_MODE, publicKey);
		byte[] encryptedByte = pkCipher.doFinal(data.getBytes());
		return encryptedByte;
	}
	
}
